import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { FcsService } from "../../service/fcs.service";
import { Region } from "../../shared-component/class/instance";
import { debounceTime, distinctUntilChanged, first, map, switchMap } from 'rxjs/operators';
import { Observable, Subscriber } from 'rxjs';
import { randomBytes } from 'crypto';


@Component({
  selector: 'app-application-create',
  templateUrl: './application-create.component.html',
  styleUrls: ['./application-create.component.less']
})
export class ApplicationCreateComponent implements OnInit {
  @Input() applicationInstance;
  @Input() region: Region;
  applicationCreateForm: FormGroup;
  nameDes = '由小写字母、数字、中文和中划线组成，长度不超过20个字符，不能以中划线开头和结尾';
  isReadonly: boolean = false;
  constructor(private fb: FormBuilder,
    private fcsService: FcsService,
    private msgService: NzMessageService) {
    this.applicationCreateForm = this.fb.group({
      name: ['', [Validators.required, this.nameValidator], [this.nameDuplicateValidator()]],
      description: ['', [Validators.maxLength(500), this.descriptionValid]]
    });
  }

  ngOnInit() {
    // 添加时间戳和随机数字段
    this.applicationCreateForm.addControl('timestamp', new FormControl(Date.now()));
    this.applicationCreateForm.addControl('nonce', new FormControl(randomBytes(5).toString(36).substring(0, 9)));
    this.applicationInstance && this.dataInit();
  }

  dataInit() {
    this.applicationCreateForm.get("name").disable();
    this.setControlVal('name', this.applicationInstance.displayName);
    this.setControlVal('description', this.applicationInstance.description);
  }
  /**
   * 根据name返回表单控件实例
   * @param {*} name
   * @returns
   * @memberof GroupCreateComponent
   */
  getValidateForm(name: string | (string | number)[]) {
    return this.applicationCreateForm.get(name);
  }

  /**
   * 名称校验
   * @param {FormControl} control 控件实例
   */
  nameValidator(control: FormControl): any {
    let name: string = control.value;
    let pattern = new RegExp('^[a-z0-9\u4e00-\u9fa5][-a-z0-9\u4e00-\u9fa5]{0,18}[a-z0-9\u4e00-\u9fa5]$'); // 含 '-'
    let pattern2 = new RegExp('^[a-z0-9\u4e00-\u9fa5]{1,20}$');//不含
    if (name.indexOf('-') >= 0) {
      if (!pattern.test(name)) {
        return { name: true };
      }
    } else {
      if (!pattern2.test(name)) {
        return { name: true };
      }
    }
    return null;
  }

  nameDuplicateValidator() {
    return (control: FormControl): any => {
      return control.valueChanges.pipe(
        distinctUntilChanged(),
        debounceTime(400),
        switchMap(() => this.isUserNameExist(control.value)),
        map(res => res['exist'] === true ? { duplicated: true } : null),
        first()
      );
    };
  }

  isUserNameExist(name: string): Observable<any> {
    if ((this && !this.applicationInstance && name) || (this.applicationInstance && name && name !== this.applicationInstance.displayName)) {
      return this.fcsService.determineGroupDuplicate(name);
    }
    return new Observable((observer: Subscriber<any>) => {
      setTimeout(() => {
        observer.next({ exist: false });
      }, 2000);
    });
  }

  descriptionValid(control: FormControl): any {
    let des: string = control.value;
    // 最大支持500个英文字母、数字、空格、逗号、句号、中文
    let pattern = new RegExp('^[a-zA-Z0-9 ,，。.\u4e00-\u9fa5]{0,500}$');
    if (!des) {
      return null;
    }
    if (!pattern.test(des)) {
      return { description: true };
    }
    return null;
  }

  /**
   * 为表单控件赋值
   * @param {string} formControlName 控件名称
   * @param {(string | boolean)} val 设置的值
   * @memberof APICreateRestComponent
   */
  setControlVal(formControlName: string, val) {
    this.applicationCreateForm.get(formControlName).patchValue(val);
  }

  /**
   * 提交表单
   *
   * @returns {boolean}
   * @memberof GroupCreateComponent
   */
  submitForm(): Promise<boolean> {
    let group = this.applicationCreateForm as FormGroup;
    let skip1 = '';
    if (this.applicationInstance && this.applicationCreateForm.get('name').value === this.applicationInstance.displayName) {
      skip1 = 'name';
    }
    for (const i in group.controls) {
      if (i === skip1) {
        group.controls[i].clearValidators();
        group.controls[i].clearAsyncValidators();
        group.controls[i].updateValueAndValidity();
      } else {
        group.controls[i].markAsDirty();
        group.controls[i].updateValueAndValidity();
      }
    }
    return new Promise((resolve, reject) => {
      const interval = setInterval(() => {
        if (!group.pending) {
          clearInterval(interval);
          if (!group.valid) {
            resolve(false);
          } else {
            this.isReadonly = true;
            let param: { [index: string]: any } = {};
            // 设置参数
            param['displayName'] = this.applicationCreateForm.get('name').value;
            param['description'] = this.applicationCreateForm.get('description').value;
            if (this.applicationInstance && this.applicationInstance.id) {
              // 进行编辑请求
              this.fcsService.updateGroup(this.applicationInstance.id, param).subscribe(
                data => {
                  this.isReadonly = false;
                  if (data && data.displayName) {
                    resolve(true);
                    this.msgService.success(data['message'] || '应用配置成功！');
                  } else {
                    resolve(false);
                    this.msgService.error(data.message);
                  }
                },
                err => {
                  this.isReadonly = false;
                  resolve(false);
                }
              );
            } else {
              // 进行创建请求
              param['regionCode'] = this.region.regionCode;
              param['regionName'] = this.region.regionName;
              this.fcsService.createGroup(param).subscribe(data => {
                this.isReadonly = false;
                if (data && data.name) {
                  resolve(true);
                  this.msgService.success(data['message'] || '应用创建成功！');
                } else {
                  this.isReadonly = false;
                  resolve(false);
                  this.msgService.error(data['message']);
                }
              }, err => {
                this.isReadonly = false;
                resolve(false);
              });
            }
          }
        }
      }, 500);
    });
  }

  ngOnDestroy() {

  }

}
